// 设置文件
// import setting from '@/setting.js'
import { baseRouterMap, asyncRouterMap } from '@/router/baseRouter';

import { getUserPermissionMenu, getAllMenuList } from '@/api/user/user';
import { SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS } from 'constants';


/**
 * 通过authority判断是否与当前用户权限匹配
 * @param menus
 * @param route
 */
function hasPermission(menus, route) {
  if (route.authority) {
    if (menus[route.authority] !== undefined) {
      return menus[route.authority];
    } else {
      return false;
    }
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, menus, menuDatas) {
 
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(menus, route)) {
      route.name = menuDatas[route.authority].title;
      route.icon = menuDatas[route.authority].icon;
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, menus, menuDatas);
      }
      return true
    }
    return false
  })
  return accessedRouters
}


export default {
  namespaced: true,
  state: {
    routers: baseRouterMap,
    addRouters: [],

    userPermissMenus: [],
    allMenus: [],

    // 顶栏菜单
    header: [],
    // 侧栏菜单
    aside: [],
    // 侧边栏收缩
    asideCollapse: false,

    // 是否固定头部
    isfixHeader: false,

    // 是否固定侧边栏
    isfixMenu: false
  },
  getters: {
      g_addRouters(state){
        return state.addRouters;
      }
  },
  actions: {
    /**
     * 设置侧边栏展开或者收缩
     * @param {Object} state vuex state
     * @param {Boolean} collapse is collapse
     */
    asideCollapseSet({ state, dispatch }, collapse) {
      return new Promise(async resolve => {
        // store 赋值
        state.asideCollapse = collapse;

        // end
        resolve();
      });
    },
    /**
     * 切换侧边栏展开和收缩
     * @param {Object} state vuex state
     */
    asideCollapseToggle({ state, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值
        state.asideCollapse = !state.asideCollapse;

        // end
        resolve();
      });
    },
    /**
     * 从持久化数据读取侧边栏展开或者收缩
     * @param {Object} state vuex state
     */
    asideCollapseLoad({ state, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值

        // end
        resolve();
      });
    },
    fnGetUserPermissMenus: ({ commit, rootState, state }) => {
     
      let params = {
        token: rootState.base.user.token
      };
      return new Promise(resolve => {
        getUserPermissionMenu(params).then(data => {
          state.userPermissMenus = data;
          resolve();
        });
      });
    },
    fnGetAllMenus: ({ commit, state }) => {

      return new Promise(resolve => {
        getAllMenuList().then(data => {
          state.allMenus = data;
          resolve();
        });
      });
    },
    fnGenerateRoutes: ({ commit, dispatch,state }, menus) => {
      return new Promise(async resolve => {
        await dispatch(
          'base/menu/fnGetUserPermissMenus',
          {},
          {
            root: true
          }
        );

        await dispatch(
          'base/menu/fnGetAllMenus',
          {},
          {
            root: true
          }
        );
        let {
          allMenus,
          userPermissMenus
        } = state;
        let menuDatas = {};
        if(allMenus && Array.isArray(allMenus)){
          allMenus.forEach(item => {
            menuDatas[item.code] = item;
          })
        }
        if(Array.isArray(menus.menus)){
          let arr = menus.menus;
          menus = {};
          arr.forEach(item => {
            menus[item.code] = item;
          })
        }

        const accessedRouters = filterAsyncRouter(asyncRouterMap, menus, menuDatas);
        console.log(accessedRouters);
        commit('s_routers', accessedRouters);
        resolve(accessedRouters);
        // getAllMenuList().then(data => {
        //   const menuDatas = {};
        //   for (let i = 0; i < data.length; i++) {
        //     menuDatas[data[i].code] = data[i];
        //   }
        //   const accessedRouters = filterAsyncRouter(asyncRouterMap, menus, menuDatas);
        //   console.log(accessedRouters);
        //   commit('SET_ROUTERS', accessedRouters);
        //   resolve();
        // });
      });
    }
  },
  mutations: {
    /**
     * @description 设置顶栏菜单
     * @param {Object} state vuex state
     * @param {Array} menu menu setting
     */
    headerSet(state, menu) {
      // store 赋值
      state.header = menu;
    },
    /**
     * @description 设置侧边栏菜单
     * @param {Object} state vuex state
     * @param {Array} menu menu setting
     */
    asideSet(state, menu) {
      // store 赋值
      state.aside = menu;
    },

    s_routers: (state, routers) => {
      state.addRouters = routers;
      state.routers = baseRouterMap.concat(routers);
    }
  }
};
